package com.service.site;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.service.site.utils.JsonConverter;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping("/sso")
	public @ResponseBody String testSso(@RequestParam("params")String intSvcNo){
		logger.info("sso 호출됨. params : {}",intSvcNo);
		return "{\"RES_CD\":\"S001\"}";
	}
	
	@RequestMapping("/serviceSiteInfo")
	public @ResponseBody String testDirect(HttpServletResponse response){
		logger.info("serviceSiteInfo 호출됨.");
		String result = "well operation.";
		return result;
	}
	
	@RequestMapping("/RXServiceSiteInfo")
	public @ResponseBody ResponseEntity<String> testFromAgent(HttpServletResponse response){
		logger.info("RXServiceSiteInfo 호출됨.");
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("RES_MSG", "테스트가 잘되었습니다.");
		result.put("RES_CD", "S001");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=UTF-8");
		return new ResponseEntity<String>(JsonConverter.toJson(result), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping("/{apiType}")
	public void home(HttpServletRequest request,HttpServletResponse response,@RequestParam("params")String params,@PathVariable("apiType")String apiType) throws IOException{
		init(request, response);
		logger.info("api : {}  \t params : {}",apiType,params);
		Map<String,Object>responseMap = JsonConverter.toMap(getParams(apiType));
		Map<String, Object> paramsMap = JsonConverter.toMap(params);
		setTrsNo(responseMap, paramsMap);
		String responseJson = JsonConverter.toJson(responseMap);
		logger.info("response : {}",responseJson);
		responseResult(response, responseJson);
	}

	private void init(HttpServletRequest request, HttpServletResponse response) {
//		requestEncoding(request);
//		responseEncoding(response);
	}

	private void responseResult(HttpServletResponse response,String responseJson) throws IOException {
		PrintWriter pw = response.getWriter();
		pw.print(responseJson);
		pw.flush();
	}

	private void setTrsNo(Map<String, Object> responseMap,Map<String, Object> paramsMap) {
		String sendedTrsNo = (String) paramsMap.get("TRS_NO");
		responseMap.put("TRS_NO", sendedTrsNo);
	}
	
	public String getParams(String apiType){
		try {
			String path = "/response/"+apiType+".json";
			return IOUtils.toString(this.getClass().getResource(path), "UTF-8");
		} catch (IOException e) {
			throw new RuntimeException("지원 하지 않는 API 입니다. 요청된 API : "+apiType);
		}
	}
	
	protected void requestEncoding(HttpServletRequest request){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("request 가 utf8 형식이 아닙니다.",e);
		}
	}
	
	protected void responseEncoding(HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
	}
}
